<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Admin\Controller;

use Admin\Model\OrderModel;
use Think\AjaxPage;

class OrderController extends BaseController {

    public $order_status;
    public $pay_status;
    public $shipping_status;

    /**
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        // 订单 支付 发货状态
        $this->assign('order_status', $this->order_status);
        $this->assign('pay_status', $this->pay_status);
        $this->assign('shipping_status', $this->shipping_status);
    }

    /**
     * 订单首页
     */
    public function index() {
        $begin = date('Y/m/d', (time() - 30 * 60 * 60 * 24));
        $end = date('Y/m/d', strtotime('+1 days'));
        $this->assign('timegap', $begin . '-' . $end);
        $this->display();
    }

    /**
     * 获取首页数据
     */
    public function ajaxIndex() {
        $orderModel = new OrderModel();
        $timegap = I('timegap');
        if ($timegap) {
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        $where = array();
        I('consignee') ? $where['consignee'] = trim(I('consignee')) : false;
        if ($begin && $end) {
            $where['add_time'] = array('between', "$begin,$end");
        }
        I('order_sn') ? $where['order_sn'] = trim(I('order_sn')) : false;
        I('order_status') != '' ? $where['order_status'] = I('order_status') : false;
        I('pay_status') != '' ? $where['pay_status'] = I('pay_status') : false;
        I('pay_code') != '' ? $where['pay_code'] = I('pay_code') : false;
        I('shipping_status') != '' ? $where['shipping_status'] = I('shipping_status') : false;
        I('user_id') ? $where['user_id'] = trim(I('user_id')) : false;
        $sortOrder = I('order_by', 'DESC') . ' ' . I('sort');
        $count = M('order')->where($where)->count();
        $Page = new AjaxPage($count, 20);
        foreach ($where as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();
        $orderRs = $orderModel->getOrderList($where, $sortOrder, $Page->firstRow, $Page->listRows);
        $this->assign('orderList', $orderRs);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 获取发货订单数据
     */
    public function ajaxDelivery() {
        $orderModel = new OrderModel();
        $where = array();
        I('consignee') ? $where['consignee'] = trim(I('consignee')) : false;
        I('order_sn') != '' ? $where['order_sn'] = trim(I('order_sn')) : false;
        $shipping_status = I('shipping_status');
        $where['shipping_status'] = empty($shipping_status) ? array('neq', 1) : $shipping_status;
        $where['order_status'] = array('in', '1,2,4');
        $count = M('order')->where($where)->count();
        $Page = new AjaxPage($count, 10);
        //搜索条件下 分页赋值
        foreach ($where as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();
        $orderRs = M('order')->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order('add_time DESC')->select();
        $this->assign('orderList', $orderRs);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 订单详情
     * @param int $order_id 订单id
     */
    public function detail($order_id) {
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($order_id);
        $orderGoods = $orderModel->getOrderGoods($order_id);
        $button = $orderModel->getOrderButton($orderRs);
        $orderRemarkRs = M('order_remark')->where(array('order_id' => $order_id))->order('log_time desc')->select();
        $this->assign('order', $orderRs);
        $this->assign('action_log', $orderRemarkRs);
        $this->assign('orderGoods', $orderGoods);
        $split = count($orderGoods) > 1 ? 1 : 0;
        foreach ($orderGoods as $val) {
            if ($val['goods_num'] > 1) {
                $split = 1;
            }
        }
        $this->assign('split', $split);
        $this->assign('button', $button);
        $this->display();
    }

    /**
     * 订单编辑
     */
    public function editOrder() {
        $orderId = I('order_id');
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($orderId);
        if ($orderRs['shipping_status'] != 0) {
            $this->error('已发货订单不允许编辑');
            exit;
        }

        $orderGoods = $orderModel->getOrderGoods($orderId);
        if (IS_POST) {
            $orderRs['consignee'] = I('consignee'); // 收货人
            $orderRs['province'] = I('province'); // 省份
            $orderRs['city'] = I('city'); // 城市
            $orderRs['district'] = I('district'); // 县
            $orderRs['address'] = I('address'); // 收货地址
            $orderRs['mobile'] = I('mobile'); // 手机
            $orderRs['invoice_title'] = I('invoice_title'); // 发票
            $orderRs['admin_note'] = I('admin_note'); // 管理员备注
            $orderRs['admin_note'] = I('admin_note'); //
            $orderRs['shipping_code'] = I('shipping'); // 物流方式
            $orderRs['shipping_name'] = M('plugin')->where(array('status' => 1, 'type' => 'shipping', 'code' => I('shipping')))->getField('name');
            $orderRs['pay_code'] = I('payment'); // 支付方式
            $orderRs['pay_name'] = M('plugin')->where(array('status' => 1, 'type' => 'payment', 'code' => I('payment')))->getField('name');
            $goodsIdArr = I("goods_id");
            $newGoodsRs = $oldGoodsRs = array();
            $newOrderGoods = convert_arr_key($orderGoods, 'goods_id');

            //订单添加商品
            if ($goodsIdArr) {
                $newGoodsRs = $orderModel->getSpecGoods($goodsIdArr);
//                $goods = M('goods')->field('goods_id,')->select();
                foreach ($newGoodsRs as $key => $val) {
                    if ($val['goods_num'] === '0') { //添加库存不能小于1
                        continue;
//                        $errorName = "修改失败,{$val['goods_name']} 库存必须大于1";
//                        $this->success($errorName, U('Admin/Order/detail', array('order_id' => $orderId)), 4);
//                        die();
                    }
                    $old_stock = 0;
                    $new_stock = 0;
                    $val['order_id'] = $orderId;
                    if (array_key_exists($val['goods_id'], $newOrderGoods)) { //添加的商品是否存在原来的订单商品中
                        $num = $val['goods_num'] + $newOrderGoods[$val['goods_id']]['goods_num'];
                        if ($num > $val['goods_stock']) { //添加库存大于商品库存
                            unset($newGoodsRs[$key]);
                            continue;
//                            $errorName = "修改失败,{$val['goods_name']}超出库存";
//                            $this->success($errorName, U('Admin/Order/detail', array('order_id' => $orderId)), 4);
//                            die();
                        } else {
                            $old_stock = $num;
                        }
                        $rec_id = M('order_goods')->where("goods_id=" . $val['goods_id'] . " and order_id = " . $val['order_id'])->save(array('goods_num' => $num));
                    } else {
                        if ($val['goods_num'] > $val['goods_stock']) { //添加库存大于商品库存
                            unset($newGoodsRs[$key]);
                            continue;
//                            $errorName = "修改失败,{$val['goods_name']}超出库存";
//                            $this->success($errorName, U('Admin/Order/detail', array('order_id' => $orderId)), 4);
//                            die();
                        } else {
                            $new_stock = $val['goods_num'];
                        }
                        $rec_id = M('order_goods')->add($val);
                    }
                    if (!$rec_id)
                        $this->error('添加失败');

                    $stock = $new_stock + $old_stock;
                    if ($orderRs['pay_code'] == 'cod' && $orderRs['order_status'] == 1) { //货到付款减库存
                        add_stock($val['order_id'], $val['goods_id'], 'Dec', $stock);
                    }

                    if ($orderRs['pay_code'] != 'cod' && $orderRs['pay_status'] == 1) { //在线支付减库存
                        add_stock($val['order_id'], $val['goods_id'], 'Dec', $stock);
                    }
                    unset($num);
                }
            }

            //订单修改删除商品
            $oldGoods = I('old_goods');

            foreach ($orderGoods as $val) {
                if (empty($oldGoods[$val['rec_id']]) && strlen($oldGoods[$val['rec_id']]) === 0) {
                    $orders = M('order')->where("order_id = {$val['order_id']}")->find();
                    if ($orders['pay_status'] > 0 || $orders['pay_code'] == 'cod') {
                        add_stock($val['order_id'], $val['goods_id'], 'add');
                    }

                    M('order_goods')->where("rec_id=" . $val['rec_id'])->delete();
                    unset($orders);
                } else {


                    $findGoods = M('order')->where("order_id = {$orderRs['order_id']}")->find();
                    //已付款
                    $pay = (($newOrderGoods[$val['goods_id']]['store_count'] + $newOrderGoods[$val['goods_id']]['goods_num']) < $oldGoods[$val['rec_id']]);
                    //未付款
                    $notPay = $newOrderGoods[$val['goods_id']]['store_count'] < $oldGoods[$val['rec_id']];
                    //判断修改的库存是否大于商品的库存
                    if ((($pay && ($findGoods['pay_status'] > 0 || $findGoods['pay_code'] == 'cod')) || $oldGoods[$val['rec_id']] < 1 || ($notPay && (($findGoods['pay_status'] < 1 && $findGoods['pay_code'] != 'cod') || ($findGoods['pay_code'] == 'cod' && $findGoods['order_status'] == 0))))) {
//                        dump(($pay && ($findGoods['pay_status'] > 0 || $orderRs['pay_code'] == 'cod' && $orderRs['order_status'] == 0)));
//                        dump($oldGoods[$val['rec_id']] < 1);
//                        dump(($notPay && (($findGoods['pay_status'] < 1 && $orderRs['pay_code'] != 'cod') || ($orderRs['pay_code'] == 'cod' && $orderRs['order_status'] == 0))));
//                        die();
//                        unset($orderGoods[$key]);
//                        continue;
//                        if($oldGoods[$val['rec_id']] < 1) {
//                            $errorName = "修改失败,{$newOrderGoods[$val['goods_id']]['goods_name']} 库存不能少于1";
//                            $this->success($errorName, U('Admin/Order/detail', array('order_id' => $orderId)), 4);
//                            die();
//                        }
//                        $errorName = "修改失败,{$newOrderGoods[$val['goods_id']]['goods_name']} 库存不足，库存为{$newOrderGoods[$val['goods_id']]['store_count']}";
//                        $this->success($errorName, U('Admin/Order/detail', array('order_id' => $orderId)), 4);
//                        die();
                    } else {
                        //库存在可控范围内
                        //修改商品数量
                        if ($oldGoods[$val['rec_id']] != $val['goods_num']) {
                            $val['goods_num'] = $oldGoods[$val['rec_id']];
                            if ($findGoods['pay_status'] > 0 || ($orderRs['pay_code'] == 'cod' && $orderRs['order_status'] == 1)) {
                                $orders = M('order_goods')->where("rec_id = {$val['rec_id']}")->find();

                                $num = $orders['goods_num'] - $val['goods_num']; //原来需要的库存 - 传输过来的库存
                                if ($num > 0) {
                                    //如果是货到付款
                                    if ($orderRs['pay_code'] == 'cod' && $orderRs['order_status'] == 1) {
                                        //加库存
                                        add_stock($val['order_id'], $val['goods_id'], 'add', $num);
                                    }

                                    //非货到付款
                                    if ($orderRs['pay_code'] != 'cod') {
                                        add_stock($val['order_id'], $val['goods_id'], 'add', $num);
                                    }
                                } else if ($num < 0) {
                                    //减库存
                                    $num = abs($num);
                                    //如果是货到付款
                                    if ($orderRs['pay_code'] == 'cod' && $orderRs['order_status'] == 1) {
                                        add_stock($val['order_id'], $val['goods_id'], 'Dec', $num);
                                    }
                                    //非货到付款
                                    if ($orderRs['pay_code'] != 'cod') {
                                        add_stock($val['order_id'], $val['goods_id'], 'Dec', $num);
                                    }
                                }
                            }
                            M('order_goods')->where("rec_id=" . $val['rec_id'])->save(array('goods_num' => $val['goods_num']));
                        }
                    }

                    $oldGoodsRs[] = $val;
                }
            }
            $goodsArr = array_merge($oldGoodsRs, $newGoodsRs);
            $result = calculate_price($orderRs['user_id'], $goodsArr, $orderRs['shipping_code'], 0, $orderRs['province'], $orderRs['city'], $orderRs['district'], 0, 0, 0, 0, 0);
            if ($result['status'] < 0) {
                $this->error($result['msg']);
            }

            //修改订单费用
            $orderRs['goods_price'] = $result['result']['goods_price']; // 商品总价
            $orderRs['shipping_price'] = $result['result']['shipping_price']; //物流费
            $orderRs['order_amount'] = $result['result']['order_amount']; // 应付金额
            $orderRs['total_amount'] = $result['result']['total_amount']; // 订单总价
            $o = M('order')->where('order_id=' . $orderId)->save($orderRs);

            $l = $orderModel->orderRemarkLog($orderId, 'edit', '修改订单'); //操作日志
            if ($o && $l) {
                $this->success('修改成功', U('Admin/Order/editPrice', array('order_id' => $orderId)));
            } else {
                $this->success('修改失败，修改或添加的商品库存不足或不能为0', U('Admin/Order/detail', array('order_id' => $orderId)), 4);
            }
            exit;
        }
        // 获取省份
        $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        //获取订单城市
        $city = M('region')->where(array('parent_id' => $orderRs['province'], 'level' => 2))->select();
        //获取订单地区
        $area = M('region')->where(array('parent_id' => $orderRs['city'], 'level' => 3))->select();
        //获取支付方式
        $paymentRs = M('plugin')->where(array('status' => 1, 'type' => 'payment'))->select();
        //获取配送方式
        $shippingRs = M('plugin')->where(array('status' => 1, 'type' => 'shipping'))->select();

        $this->assign('order', $orderRs);
        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('area', $area);
        $this->assign('orderGoods', $orderGoods);
        $this->assign('shippingList', $shippingRs);
        $this->assign('payment_list', $paymentRs);
        $this->display();
    }

    /**
     * 拆分订单
     */
    public function splitOrder() {
        $orderId = I('order_id');
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($orderId);
        if ($orderRs['shipping_status'] != 0) {
            $this->error('已发货订单不允许编辑');
            exit;
        }
        $orderGoods = $orderModel->getOrderGoods($orderId);
        if (IS_POST) {
            $data = I('post.');
            //先处理原单剩余商品和原订单信息
            $oldGoods = I('old_goods');
            foreach ($orderGoods as $val) {
                if (empty($oldGoods[$val['rec_id']])) {
                    M('order_goods')->where("rec_id=" . $val['rec_id'])->delete();
                } else {
                    if ($oldGoods[$val['rec_id']] != $val['goods_num']) {
                        $val['goods_num'] = $oldGoods[$val['rec_id']];
                        M('order_goods')->where("rec_id=" . $val['rec_id'])->save(array('goods_num' => $val['goods_num']));
                    }
                    $oldArr[] = $val; //剩余商品
                }
                $allGoods[$val['rec_id']] = $val; //所有商品信息
            }
            $result = calculate_price($orderRs['user_id'], $oldArr, $orderRs['shipping_code'], 0, $orderRs['province'], $orderRs['city'], $orderRs['district'], 0, 0, 0, 0);
            if ($result['status'] < 0) {
                $this->error($result['msg']);
            }
            //修改订单费用
            $res['goods_price'] = $result['result']['goods_price']; // 商品总价
            $res['order_amount'] = $result['result']['order_amount']; // 应付金额
            $res['total_amount'] = $result['result']['total_amount']; // 订单总价
            M('order')->where("order_id=" . $orderId)->save($res);
            //原单处理结束
            //新单处理
            for ($i = 1; $i < 20; $i++) {
                if (!empty($_POST[$i . '_old_goods'])) {
                    $splitGoods[] = $_POST[$i . '_old_goods'];
                }
            }

            foreach ($splitGoods as $key => $vrr) {
                foreach ($vrr as $k => $v) {
                    $allGoods[$k]['goods_num'] = $v;
                    $brr[$key][] = $allGoods[$k];
                }
            }

            foreach ($brr as $goods) {
                $result = calculate_price($orderRs['user_id'], $goods, $orderRs['shipping_code'], 0, $orderRs['province'], $orderRs['city'], $orderRs['district'], 0, 0, 0, 0);
                if ($result['status'] < 0) {
                    $this->error($result['msg']);
                }
                $newOrder = $orderRs;
                $newOrder['order_sn'] = date('YmdHis') . mt_rand(1000, 9999);
                $newOrder['parent_sn'] = $orderRs['order_sn'];
                //修改订单费用
                $newOrder['goods_price'] = $result['result']['goods_price']; // 商品总价
                $newOrder['order_amount'] = $result['result']['order_amount']; // 应付金额
                $newOrder['total_amount'] = $result['result']['total_amount']; // 订单总价
                $newOrder['add_time'] = time();
                unset($newOrder['order_id']);
                $newOrderId = M('order')->add($newOrder);
                foreach ($goods as $vv) {
                    $vv['order_id'] = $newOrderId;
                    unset($vv['rec_id']);
                    $nid = M('order_goods')->add($vv);
                }
            }

            $this->success('操作成功', U('Admin/Order/detail', array('order_id' => $orderId)));
            exit;
        }

        foreach ($orderGoods as $val) {
            $brr[$val['rec_id']] = array('goods_num' => $val['goods_num'], 'goods_name' => getSubstr($val['goods_name'], 0, 35) . $val['spec_key_name']);
        }
        $this->assign('order', $orderRs);
        $this->assign('goods_num_arr', json_encode($brr));
        $this->assign('orderGoods', $orderGoods);
        $this->display();
    }

    /**
     * 价钱修改
     */
    public function editPrice($order_id) {
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($order_id);
        $this->editable($orderRs);
        if (IS_POST) {
            $adminId = session('admin_id');
            if (empty($adminId)) {
                $this->error('非法操作');
                exit;
            }
            $update['discount'] = I('post.discount');
            $update['shipping_price'] = I('post.shipping_price');
            $update['order_amount'] = $orderRs['order_amount'] + $update['shipping_price'] - $update['discount'] - $orderRs['user_money'] - $orderRs['integral_money'] - $orderRs['coupon_price'];
            $row = M('order')->where(array('order_id' => $order_id))->save($update);
            if (!$row) {
                $this->success('没有更新数据', U('Admin/Order/editPrice', array('order_id' => $order_id)));
            } else {
                $this->success('操作成功', U('Admin/Order/detail', array('order_id' => $order_id)));
            }
            exit;
        }
        $this->assign('order', $orderRs);
        $this->display();
    }

    /**
     * 订单删除
     * @param int $orderId 订单id
     */
    public function deleteOrder($orderId) {
        $orderModel = new OrderModel();
        $del = $orderModel->delOrder($orderId);
        if ($del) {
            $this->success('删除订单成功');
        } else {
            $this->error('订单删除失败');
        }
    }

    /**
     * 订单取消付款
     */
    public function payCancel($orderId) {
        $orderRs = M('order')->where("order_id=$orderId")->find();
        if (I('remark')) {
            $data = I('post.');
            $note = array('退款到用户余额', '已通过其他方式退款', '不处理，误操作项');
            if ($data['refundType'] == 0 && $data['amount'] > 0) {
                userLog($data['user_id'], $data['amount'], 0, '退款到用户余额', $orderRs['order_id'], $orderRs['order_sn']);
            }
            $orderModel = new OrderModel();
            $orderModel->orderProcessHandle($data['order_id'], 'payCancel');
            $d = $orderModel->orderRemarkLog($data['order_id'], 'payCancel', $data['remark'] . ':' . $note[$data['refundType']]);
            if ($d) {
                exit("<script>window.parent.pay_callback(1);</script>");
            } else {
                exit("<script>window.parent.pay_callback(0);</script>");
            }
        } else {
            $this->assign('order', $orderRs);
            $this->display();
        }
    }

    /**
     * 订单打印
     */
    public function orderPrint() {
        $orderId = I('order_id');
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($orderId);
        $orderRs['province'] = getRegionName($orderRs['province']);
        $orderRs['city'] = getRegionName($orderRs['city']);
        $orderRs['district'] = getRegionName($orderRs['district']);
        $orderRs['full_address'] = $orderRs['province'] . ' ' . $orderRs['city'] . ' ' . $orderRs['district'] . ' ' . $orderRs['address'];
        $orderGoods = $orderModel->getOrderGoods($orderId);
        $shop = xrkCache('shop_info');
        $this->assign('order', $orderRs);
        $this->assign('shop', $shop);
        $this->assign('orderGoods', $orderGoods);
        $template = I('template', 'print');
        $this->display($template);
    }

    /**
     * 快递单打印
     */
    public function shippingPrint1() {
        $code = I('get.code');
        $id = I('get.order_id');
        $shipping = M('plugin')->where(array('code' => $code, 'type' => 'shipping'))->find();
        if (!$shipping)
            $this->error('物流插件不存在', U('Admin/Index/index'));
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($id);
        if (!$orderRs)
            $this->error('订单不存在');
        if (!file_exists(APP_PATH . "Admin/View/Plugin/shipping/{$code}_print.html"))
            $this->error('请先在插件中心设置打印模板', U('Admin/Index/index'));
        //获取商店信息
        $shop = xrkCache('shop_info');
        $orderRs['province'] = getRegionName($orderRs['province']);
        $orderRs['city'] = getRegionName($orderRs['city']);
        $orderRs['district'] = getRegionName($orderRs['district']);
        $orderRs['full_address'] = $orderRs['province'] . ' ' . $orderRs['city'] . ' ' . $orderRs['district'] . ' ' . $orderRs['address'];
        $this->assign('shop', $shop);
        $this->assign('order', $orderRs);
        $this->display("Plugin/shipping/{$code}_print");
    }

    /**
     * 打印快递单
     */
    public function shippingPrint() {
        $orderId = I('get.order_id');
        $orderMod = new OrderModel();
        $orderRs = $orderMod->getOrderInfo($orderId);
        $shipping = M('plugin')->where(array('code' => $orderRs['shipping_code'], 'type' => 'shipping'))->find();
        if (!$shipping) {
            $this->error('物流插件不存在');
        }
        if (empty($shipping['config_value'])) {
            $this->error('请设置' . $shipping['name'] . '打印模板');
        }
        $shop = xrkCache('shop_info');
        $shop['province'] = empty($shop['province']) ? '' : getRegionName($shop['province']);
        $shop['city'] = empty($shop['city']) ? '' : getRegionName($shop['city']);
        $shop['district'] = empty($shop['district']) ? '' : getRegionName($shop['district']);

        $orderRs['province'] = getRegionName($orderRs['province']);
        $orderRs['city'] = getRegionName($orderRs['city']);
        $orderRs['district'] = getRegionName($orderRs['district']);
        if (empty($shipping['config'])) {
            $config = array('width' => 840, 'height' => 480, 'offset_x' => 0, 'offset_y' => 0);
            $this->assign('config', $config);
        } else {
            $this->assign('config', unserialize($shipping['config']));
        }
        $templateRs = array("发货点-名称", "发货点-联系人", "发货点-电话", "发货点-省份", "发货点-城市",
            "发货点-区县", "发货点-手机", "发货点-详细地址", "收件人-姓名", "收件人-手机", "收件人-电话",
            "收件人-省份", "收件人-城市", "收件人-区县", "收件人-邮编", "收件人-详细地址", "时间-年", "时间-月",
            "时间-日", "时间-当前日期", "订单-订单号", "订单-备注", "订单-配送费用");
        $contentRs = array($shop['store_name'], $shop['contact'], $shop['phone'], $shop['province'], $shop['city'],
            $shop['district'], $shop['phone'], $shop['address'], $orderRs['consignee'], $orderRs['mobile'], $orderRs['phone'],
            $orderRs['province'], $orderRs['city'], $orderRs['district'], $orderRs['zipcode'], $orderRs['address'], date('Y'), date('M'),
            date('d'), date('Y-m-d'), $orderRs['order_sn'], $orderRs['admin_note'], $orderRs['shipping_price'],
        );
        $shipping['config_value'] = str_replace($templateRs, $contentRs, $shipping['config_value']);
        $this->assign('shipping', $shipping);
        $this->display("Plugin/printExpress");
    }

    /**
     * 生成发货单
     */
    public function deliveryHandle() {
        $orderModel = new OrderModel();
        $post = I('post.');
        $res = $orderModel->deliveryHandle($post);
        if ($res) {
//            \Org\Job\addJoe::Joe(new \Job\AutoReceipt($data['order_id']))->delay(60)->onQueue('order')->push(); //添加自动收货任务
            $this->success('操作成功', U('Admin/Order/deliveryInfo', array('order_id' => $post['order_id'])));
        } else {
            $this->success('操作失败', U('Admin/Order/deliveryInfo', array('order_id' => $post['order_id'])));
        }
    }

    /**
     * 发货单信息
     */
    public function deliveryInfo() {
        $orderId = I('order_id');
        $orderModel = new OrderModel();
        $orderRs = $orderModel->getOrderInfo($orderId);
        $orderGoods = $orderModel->getOrderGoods($orderId);
        $deliveryRs = M('delivery')->where('order_id=' . $orderId)->select();
        $this->assign('order', $orderRs);
        $this->assign('orderGoods', $orderGoods);
        if ($deliveryRs) {
            $orderRs['invoice_no'] = $deliveryRs[count($deliveryRs) - 1]['invoice_no'];
        }
        $this->assign('delivery_record', $deliveryRs); //发货记录
        $this->display();
    }

    /**
     * 发货单列表
     */
    public function deliveryList() {
        $this->display();
    }

    /**
     * 获取退货订单数据
     */
    public function ajaxReturnList() {
        $orderSn = trim(I('order_sn'));
        $orderBy = I('order_by') ? I('order_by') : 'id';
        $sortOrder = I('sort_order') ? I('sort_order') : 'desc';

        $where = " 1 = 1 ";
        $orderSn && $where .= " and order_sn like '%$orderSn%' ";
        if (I('status') != -1) {
            $status = I('status');
            empty($orderSn) && $where .= " and status = '$status' ";
        }
        $count = M('order_return')->where($where)->count();
        $Page = new AjaxPage($count, 13);
        $show = $Page->show();
        $list = M('order_return')->where($where)->order("$orderBy $sortOrder")->limit("{$Page->firstRow},{$Page->listRows}")->select();
        $goodsIdArr = get_arr_column($list, 'goods_id');
        if (!empty($goodsIdArr))
            $goodsList = M('goods')->where("goods_id in (" . implode(',', $goodsIdArr) . ")")->getField('goods_id,goods_name');
        $this->assign('goodsList', $goodsList);
        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
    }

    /**
     * 删除某个退换货申请
     */
    public function returnDel() {
        $id = I('get.id');
        M('order_return')->where("id = $id")->delete();
        $this->success('成功删除!');
    }

    /**
     * 退换货操作
     */
    public function returnInfo() {
        $id = I('id');
        $orderReturn = M('order_return')->where("id= $id")->find();
        if ($orderReturn['imgs'])
            $orderReturn['imgs'] = explode(',', $orderReturn['imgs']);
        $user = M('users')->where("user_id = {$orderReturn[user_id]}")->find();
        $orderRs = M('order')->where("order_id = {$orderReturn[order_id]}")->find();
        $goods = M('goods')->where("goods_id = {$orderReturn[goods_id]}")->find();
        $msgType = array('退换', '换货');
        $msgStatus = array('未处理', '处理中', '已完成');
        if (IS_POST) {
            $data['type'] = I('type');
            $data['status'] = I('status');
            $data['remark'] = I('remark');
            $time = time();
            $note = "退换货:{$msgType[$data['type']]}, 状态:{$msgStatus[$data['status']]},处理备注：{$data['remark']}";
            $result = M('order_return')->where("id= $id")->save($data);
            if ($data['status'] == 2 && $result) {
                $type = ($data['type'] == 1) ? 2 : 3;
                $where = " order_id = " . $orderReturn['order_id'] . " and goods_id=" . $orderReturn['goods_id'];
                M('order_goods')->where($where)->save(array('is_send' => $type)); //更改商品状态

                if ($msgType[$data['type']] == '退换' && $msgStatus[$data['status']] == '已完成') {
                    $orderRs['integral']; //订单使用积分
                    add_stock($orderReturn['order_id'], $orderReturn['goods_id']);
                    //修改佣金待处理
//                    order_comm_amount($orderRs, $orderReturn['goods_id']);
                    $orderResult = order_amount($orderRs, $orderReturn['goods_id']); //退货成功后修改订单佣金值，并返回用户佣金
                    edit_bonus_log($orderResult); //退货成功后修改分成表对应的佣金

                    $confirm_time = $orderRs['confirm_time']; //确认收货时间
                    $find = M('order_return')->where('order_id = ' . $orderReturn['order_id'] . ' and status < 2')->find();
                    if ($time >= $confirm_time + 60 * 60 * 24 * 7 && !$find) { //如果找不到未处理完的订单并且操作的时间大于7天
//                        addJoe::Joe(new AutoSuccessOrder($orderReturn['order_id']))->delay(60 * 60 * 24 * 7)->onQueue('order')->push();
                    }
                }
            }

            $orderModel = new OrderModel();
            $log = $orderModel->orderRemarkLog($orderReturn[order_id], 'refund', $note);

            $this->success('修改成功!');
            exit;
        }
        $this->assign('id', $id);
        $this->assign('user', $user); // 用户
        $this->assign('order', $orderRs); // 订单
        $this->assign('goods', $goods); // 商品
        $this->assign('orderReturn', $orderReturn); // 退换货               
        $this->display();
    }

    /**
     * 生成申请退货单
     */
    public function addOrderReturn() {
        $orderId = I('order_id');
        $goodsId = I('goods_id');
        $orderReturn = M('order_return')->where("order_id = $orderId and goods_id = $goodsId")->find();
        if (!empty($orderReturn)) {
            $this->error('已经提交过退货申请!', U('Admin/Order/returnList'));
            exit;
        }
        $orderRs = M('order')->where("order_id = $orderId")->find();
        $data['order_id'] = $orderId;
        $data['order_sn'] = $orderRs['order_sn'];
        $data['goods_id'] = $goodsId;
        $data['addtime'] = time();
        $data['user_id'] = $orderRs['user_id'];
        $data['remark'] = '管理员申请退换货';
        M('order_return')->add($data);
        $this->success('申请成功,现在去处理退货', U('Admin/Order/returnList'));
        exit;
    }

    /**
     * 订单操作
     * @param $id
     */
    public function orderRemark() {
        $orderModel = new OrderModel();
        $action = I('get.type');
        $orderId = I('get.order_id');
        if ($action && $orderId) {
            $a = $orderModel->orderProcessHandle($orderId, $action);
            $res = $orderModel->orderRemarkLog($orderId, $action, I('note'));
            if ($res && $a) {
                exit(json_encode(array('status' => 1, 'msg' => '操作成功')));
            } else {
                exit(json_encode(array('status' => 0, 'msg' => '操作失败')));
            }
        } else {
            $this->error('参数错误', U('Admin/Order/detail', array('order_id' => $orderId)));
        }
    }

    /**
     * 订单日志 
     */
    public function orderLog() {
        $timegap = I('timegap');
        if ($timegap) {
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        $where = array();
        $log = M('order_remark');
        if ($begin && $end) {
            $where['log_time'] = array('between', "$begin,$end");
        }
        $adminId = I('admin_id');
        if ($adminId > 0) {
            $where['action_user'] = $adminId;
        }
        $count = $log->where($where)->count();
        $Page = new \Think\Page($count, 20);
        foreach ($where as $key => $val) {
            $Page->parameter[$key] = urlencode($val);
        }
        $show = $Page->show();
        $list = $log->where($where)->order('action_id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('list', $list);
        $this->assign('page', $show);
        $admin = M('admin')->getField('admin_id,user_name');
        $this->assign('admin', $admin);
        $this->display();
    }

    /**
     * 检测订单是否可以编辑
     * @param $orderRs 订单对象
     */
    private function editable($orderRs) {
        if ($orderRs['shipping_status'] != 0) {
            $this->error('已发货订单不允许编辑');
            exit;
        }
        return;
    }

    /**
     * 导出订单
     */
    public function exportOrder() {
        $where = 'where 1=1 ';
        $consignee = I('consignee');
        if ($consignee) {
            $where .= " AND consignee like '%$consignee%' ";
        }
        $orderSn = I('order_sn');
        if ($orderSn) {
            $where .= " AND order_sn = '$orderSn' ";
        }
        if (I('order_status')) {
            $where .= " AND order_status = " . I('order_status');
        }

        $timegap = I('timegap');
        if ($timegap) {
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $where .= " AND add_time>$begin and add_time<$end ";
        }

        $sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
        $orderRs = D()->query($sql);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
        $strTable .= '</tr>';
        if (is_array($orderRs)) {
            $region = M('region')->getField('id,name');
            foreach ($orderRs as $k => $val) {
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['order_sn'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['create_time'] . ' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['consignee'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . "{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['address']}" . ' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['mobile'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['goods_price'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['order_amount'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['pay_name'] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $this->pay_status[$val['pay_status']] . '</td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $this->shipping_status[$val['shipping_status']] . '</td>';
                $orderGoods = D('order_goods')->where('order_id=' . $val['order_id'])->select();
                $strGoods = "";
                foreach ($orderGoods as $goods) {
                    $strGoods .= "商品编号：" . $goods['goods_sn'] . " 商品名称：" . $goods['goods_name'];
                    if ($goods['spec_key_name'] != '')
                        $strGoods .= " 规格：" . $goods['spec_key_name'];
                    $strGoods .= "<br />";
                }
                unset($orderGoods);
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $strGoods . ' </td>';
                $strTable .= '</tr>';
            }
        }
        $strTable .= '</table>';
        unset($orderRs);
        downloadExcel($strTable, 'order');
        exit();
    }

    /**
     * 退货单列表
     */
    public function returnList() {
        $this->display();
    }

    /**
     * 添加订单
     */
    public function addOrder() {
        $orderRs = array();
        $province = M('region')->where(array('parent_id' => 0, 'level' => 1))->select();
        $city = M('region')->where(array('parent_id' => $orderRs['province'], 'level' => 2))->select();
        $area = M('region')->where(array('parent_id' => $orderRs['city'], 'level' => 3))->select();
        $shippingRs = M('plugin')->where(array('status' => 1, 'type' => 'shipping'))->select();
        $paymentRs = M('plugin')->where(array('status' => 1, 'type' => 'payment'))->select();
        if (IS_POST) {
            $orderRs['user_id'] = I('user_id'); // 用户id 可以为空
            $orderRs['consignee'] = I('consignee'); // 收货人
            $orderRs['province'] = I('province'); // 省份
            $orderRs['city'] = I('city'); // 城市
            $orderRs['district'] = I('district'); // 县
            $orderRs['address'] = I('address'); // 收货地址
            $orderRs['mobile'] = I('mobile'); // 手机
            $orderRs['invoice_title'] = I('invoice_title'); // 发票
            $orderRs['admin_note'] = I('admin_note'); // 管理员备注
            $orderRs['order_sn'] = date('YmdHis') . mt_rand(1000, 9999); // 订单编号;
            $orderRs['admin_note'] = I('admin_note'); //
            $orderRs['add_time'] = time(); //
            $orderRs['shipping_code'] = I('shipping'); // 物流方式
            $orderRs['shipping_name'] = M('plugin')->where(array('status' => 1, 'type' => 'shipping', 'code' => I('shipping')))->getField('name');
            $orderRs['pay_code'] = I('payment'); // 支付方式
            $orderRs['pay_name'] = M('plugin')->where(array('status' => 1, 'type' => 'payment', 'code' => I('payment')))->getField('name');

            $goodsIdArr = I("goods_id");
            $orderModel = new OrderModel();
            $orderGoods = $orderModel->getSpecGoods($goodsIdArr);
            $result = calculate_price($orderRs['user_id'], $orderGoods, $orderRs['shipping_code'], 0, $orderRs[province], $orderRs[city], $orderRs[district], 0, 0, 0, 0);
            if ($result['status'] < 0) {
                $this->error($result['msg']);
            }

            $orderRs['goods_price'] = $result['result']['goods_price']; // 商品总价
            $orderRs['shipping_price'] = $result['result']['shipping_price']; //物流费
            $orderRs['order_amount'] = $result['result']['order_amount']; // 应付金额
            $orderRs['total_amount'] = $result['result']['total_amount']; // 订单总价
            $orderId = M('order')->add($orderRs);
            if ($orderId) {
                foreach ($orderGoods as $key => $val) {
                    $val['order_id'] = $orderId;
                    $rec_id = M('order_goods')->add($val);
                    if (!$rec_id)
                        $this->error('添加失败');
                }
//                minus_stock($orderId);//删除库存
                $this->success('添加商品成功', U("Admin/Order/detail", array('order_id' => $orderId)));
                exit();
            }
            else {
                $this->error('添加失败');
            }
        }
        $this->assign('shippingList', $shippingRs);
        $this->assign('payment_list', $paymentRs);
        $this->assign('province', $province);
        $this->assign('city', $city);
        $this->assign('area', $area);
        $this->display();
    }

    /**
     * 搜索商品
     */
    public function searchGoods() {
        $brandRs = M("brand")->select();
        $categoryRs = M("goods_cat")->select();
        $this->assign('categoryList', $categoryRs);
        $this->assign('brandList', $brandRs);
        $where = ' is_on_sale = 1 ';
        I('intro') && $where = "$where and " . I('intro') . " = 1";
        if (I('cat_id')) {
            $this->assign('cat_id', I('cat_id'));
            $grandson_ids = getGoodsSubCat(I('cat_id'));
            $where = " $where  and cat_id in(" . implode(',', $grandson_ids) . ") "; // 初始化搜索条件
        }
        if (I('brand_id')) {
            $this->assign('brand_id', I('brand_id'));
            $where = "$where and brand_id = " . I('brand_id');
        }
        if (!empty($_REQUEST['keywords'])) {
            $this->assign('keywords', I('keywords'));
            $where = "$where and (goods_name like '%" . I('keywords') . "%' or keywords like '%" . I('keywords') . "%')";
        }
        $goodsList = M('goods')->where($where)->order('goods_id DESC')->limit(10)->select();

        foreach ($goodsList as $key => $val) {
            $spec_goods = M('goods_stock')->where("goods_id = {$val['goods_id']}")->select();
            $goodsList[$key]['spec_goods'] = $spec_goods;
        }
        $this->assign('goodsList', $goodsList);
        $this->display();
    }

    /**
     * 获取订单数量
     */
    public function ajaxOrderNotice() {
        echo M('order')->where("order_status=0 and (pay_status=1 or pay_code='cod')")->count();
    }

}
